import { vscode } from '@/utils/vscode'

export interface RequestConfig {
    model: string, // 文本使用的模型
    type: string; // txt是纯文本请求，img是携带图片请求
    additional_messages?: any;
}
  
interface RequestResponse {
    data: any;
    status: number;
    headers?: Record<string, string>;
}
  
class VSCodeRequest {
    private static instance: VSCodeRequest;
    private messageHandlers: Map<string, (event: MessageEvent) => void>;
  
    private constructor() {
      this.messageHandlers = new Map();
      window.addEventListener('message', this.handleMessage.bind(this));
    }
  
    public static getInstance(): VSCodeRequest {
      if (!VSCodeRequest.instance) {
        VSCodeRequest.instance = new VSCodeRequest();
      }
      return VSCodeRequest.instance;
    }
  
    private handleMessage(event: MessageEvent) {
      const message = event.data;
      const handler = this.messageHandlers.get(message.requestId);
      if (handler) {
        handler(event);
      }
    }
  
    public async request(config: RequestConfig): Promise<RequestResponse> {
      return new Promise((resolve, reject) => {
        const requestId = Date.now().toString();
  
        const handler = (event: MessageEvent) => {
          const message = event.data;
          if (message.requestId === requestId) {
            this.messageHandlers.delete(requestId);
            
            if (message.command === 'httpResponse') {
              resolve({
                data: message.data,
                status: message.status,
                headers: message.headers
              });
            } else if (message.command === 'httpError') {
              reject(message.error);
            }
          }
        };
  
        this.messageHandlers.set(requestId, handler);
  
        // 发送请求到插件端
        vscode.postMessage({
          command: 'httpRequest',
          requestId,
          ...config
        });
      });
    }
  
    public async streamRequest(config: RequestConfig, onCbRequestId: (requestId: string) => void, onReasoningData: (data: string) => void, onData: (data: string) => void): Promise<void> {
      return new Promise((resolve, reject) => {
        const requestId = Date.now().toString();
        onCbRequestId(requestId);

        const handler = (event: MessageEvent) => {
          const message = event.data;
          if (message.requestId === requestId) {
            if (message.command === 'sseReasoningData') {
              onReasoningData(message.data);
            } else if (message.command === 'sseData') {
              onData(message.data);
            } else if (message.command === 'sseComplete') {
              this.messageHandlers.delete(requestId);
              resolve();
            } else if (message.command === 'sseError') {
              this.messageHandlers.delete(requestId);
              reject(message.error);
            }
          }
        };
  
        this.messageHandlers.set(requestId, handler);
  
        // 发送流式请求到插件端
        vscode.postMessage({
          command: 'streamRequest',
          requestId,
          ...config
        });
      });
    }
    
    public cancel(requestId: string) {
      this.messageHandlers.delete(requestId);
      vscode.postMessage({
        command: 'chatCancel',
        requestId
      });
    }

    public dispose() {
      window.removeEventListener('message', this.handleMessage.bind(this));
      this.messageHandlers.clear();
    }
}
  
export const vscodeRequest = VSCodeRequest.getInstance();